package com.lucien.Stack;

import java.util.Scanner;

/**
 * 数组模拟栈
 */
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(4);
        String key = "";
        boolean loop = true;
        Scanner sc = new Scanner(System.in);
        while (loop){
            System.out.println("show:表示显示栈");
            System.out.println("exit:退出栈");
            System.out.println("push:表示加入数据到栈中");
            System.out.println("pop:表示从栈中取出数据");
            System.out.println("请输入你的选择");
            key = sc.next();
            switch (key){
                case "show":
                    stack.list();
                    break;
                case "exit":
                    sc.close();
                    loop = false;
                    break;
                case "push":
                    System.out.println("请输入你要添加的值");
                    int value = sc.nextInt();
                    stack.push(value);
                    break;
                case "pop":
                    try {
                        int res = stack.pop();
                        System.out.printf("输出的数据是%d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }

                    break;
            }
        }
        System.out.println("程序退出");
    }
}

//定义一个 ArrayStack 表示栈
class ArrayStack{
    private int maxsize;//栈的最大值
    private int [] stack;//数组  数据存放在该数组
    private int top = -1;//栈顶 初始值为-1

    public ArrayStack(int maxsize){
        this.maxsize = maxsize;
        stack = new int [this.maxsize];
    }

    //判断栈是否满
    public boolean isFull(){
        return top == maxsize-1;
    }

    //判断栈是否空
    public boolean isEmpty(){
        return top == -1;
    }

    //入栈push
    public  void push(int value){
        if (isFull()){
            System.out.println("栈满");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈pop
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈空，没有数据");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //显示栈
    public void list(){
        if (isEmpty()){
            System.out.println("栈空，没有数据");
            return;
        }
        //需要从栈顶开始显示数据
        for (int i = top; i >=0 ; i--) {
            System.out.printf("stack[%d] = %d\n",i,stack[i]);
        }
    }
}
